import React from 'react';
import { Form, Modal, message, InputNumber, Select } from 'antd';
import Api from 'Utils/api';
import './index.scss';

const Option = Select.Option;
const FormItem = Form.Item;
const AddForm = Form.create()(
  (props) => {
    const { form, initialValue } = props;
    const { getFieldDecorator } = form;

    return (
      <Form>
        <FormItem
          label="题型:"
        >
          {
            getFieldDecorator('question_type', {
              initialValue: initialValue ? initialValue.question_type : '',
              rules: [
                { required: true, message: '请选择体型' }
              ]
            })(
              <Select placeholder="请选择题型" style={{ width: 600 }} >
                <Option value="单选题">单选题</Option>
                <Option value="多选题">多选题</Option>
              </Select>
            )
          }
        </FormItem>
        <FormItem
          label="题数:"
        >
          {
            getFieldDecorator('amount', {
              initialValue: initialValue ? initialValue.amount : '',
              rules: [
                { required: true, message: '请输入题数' },
              ]
            })(
              <InputNumber
                placeholder="请输入题数"
                style={{ width: 600 }}
                min={1}
                max={100}
                formatter={value => value && parseInt(value, 10)}
                parser={value => value && !isNaN(parseInt(value, 10)) && parseInt(value, 10)}
              />
            )
          }
        </FormItem>
        <FormItem
          label="分值:"
        >
          {
            getFieldDecorator('score', {
              initialValue: initialValue ? initialValue.score : '',
              rules: [
                { required: true, message: '请输入分值' },
              ]
            })(
              <InputNumber placeholder="请输入分值" style={{ width: 600 }} min={1} max={100} />
            )
          }
        </FormItem>
      </Form>
    );
  }
);

class AddEditType extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      visible: false,
      loading: false,
      isAdd: false,
      record: ''
    };
  }

  showModal(record) {
    this.setState({
      visible: true,
      record: record,
      isAdd: !record
    }, () => {
      this.form.resetFields();
    });
  }

  close() {
    this.setState({
      loading: false,
      visible: false,
    });
  }
  validation(value) {
    if (!value.question_type || !value.amount || !value.score) {
      return false;
    }
    return true;
  }

  handleOk() {
    this.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const { isAdd, record } = this.state;
        const { subjectId } = this.props;
        const formValue = this.form.getFieldsValue();
        // const currentValue = isAdd ? {} : { type: this.state.record };
        if (!this.validation(formValue)) {
          message.warn('请完善信息', 3);
          return;
        }
        this.setState({ loading: true });
        const newRecord = { ...formValue };
        const self = this;
        if (!isAdd) {
          const editApi = new Api({
            method: 'PATCH',
            path: `/subjects/update_subject/${subjectId}`,
            data: newRecord,
            query: { index: record.id },
            success: () => {
              this.props.onOk();
              self.close();
            },
            error: (msg) => {
              message.error(msg);
              this.setState({ loading: false });
            }
          });
          editApi.run();
        } else {
          // console.log(newRecord);
          const addApi = new Api({
            method: 'PATCH',
            path: `/subjects/add_subject/${subjectId}`,
            data: newRecord,
            success: () => {
              this.props.onOk();
              self.close();
            },
            error: (msg) => {
              message.error(msg);
              this.setState({ loading: false });
            }
          });
          addApi.run();
        }
      }
    });
  }
  render() {
    const title = this.state.isAdd ? '新增' : '修改';
    return (
      <div>
        <Modal
          className="add-edit-modal small-modal"
          title={`${title}题型`}
          visible={this.state.visible}
          onOk={this.handleOk.bind(this)}
          onCancel={() => {
            this.close();
          }}
          confirmLoading={this.state.loading}
        >
          <AddForm
            initialValue={this.state.record ? this.state.record : {}}
            ref={(ref) => { this.form = ref; }}
          />
        </Modal>
      </div>
    );
  }
}

export default AddEditType;
